﻿using Emgu.CV;
using Emgu.CV.Structure;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using Tesseract;
namespace ICRS
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        string imgPath = "";
        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                imgPath = ofd.FileName;

                Image<Bgr, byte> img = new Image<Bgr, byte>(imgPath);
                pictureBox1.Image = img.Bitmap ;
                //pictureBox1.Image = img.Bitmap;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Image<Bgr, byte> img = new Image<Bgr, byte>(imgPath);
            img = Util.ResizeImage(img.Bitmap, new Size(512, 384));

            RotatedRect idRect = Util.IdRotatedRect(img);
           // Util.DrawRotatedRect(idRect, img);

            RotatedRect addressRect = Util.AddressRotatedRect(idRect);
          //  Util.DrawRotatedRect(addressRect, img);

            RotatedRect dateRect = Util.DateRotatedRect(idRect);
          //  Util.DrawRotatedRect(dateRect, img);

            RotatedRect sexRect = Util.SexRotatedRect(idRect);
          //  Util.DrawRotatedRect(sexRect, img);

            RotatedRect nameRect = Util.NameRotatedRect(idRect);
            //  Util.DrawRotatedRect(nameRect, img);

            double idArea = idRect.Size.Width * idRect.Size.Height;

            Bitmap id =  Util.BinImg( Util.Rote(img, idRect),15,(int)(0.00111 *idArea)).Bitmap;
            Bitmap address = Util.BinImg(Util.Rote(img, addressRect), 15, (int)(0.00111 *idArea)).Bitmap;
            Bitmap date = Util.BinImg(Util.Rote(img, dateRect), 15, (int)(0.001111 *idArea)).Bitmap;
            Bitmap sex = Util.BinImg(Util.Rote(img, sexRect), 15, (int)(0.00111 *idArea)).Bitmap;
            Bitmap name = Util.BinImg(Util.Rote(img, nameRect), 15, (int)(0.00111 *idArea)).Bitmap;
          //  MessageBox.Show(idRect.Size.Width.ToString()+","+ idRect.Size.Height.ToString());

            pictureBox2.Image = name;
            pictureBox3.Image = sex;
            pictureBox4.Image = date;
            pictureBox5.Image = address;
            pictureBox6.Image = id;

            string idText = GetNumber( GetText(id));
            dataGridView1.Rows.Clear();
            dataGridView1.Rows.Add(new object[] { "姓名", GetChinese( GetText(name)) });
            dataGridView1.Rows.Add(new object[] { "性别", GetSex( idText) });
            dataGridView1.Rows.Add(new object[] { "名族", "汉" });
            dataGridView1.Rows.Add(new object[] { "出生日期", GetDate(idText) });
            dataGridView1.Rows.Add(new object[] { "住址", GetChinese(GetText(address)) });
            dataGridView1.Rows.Add(new object[] { "身份证号", idText });

        }

        private string GetText(string imgPath)
        {
            using (var engine = new TesseractEngine("./tessdata", "chi_sim", EngineMode.Default))
            {
                using (var image = new Bitmap(imgPath))
                {
                    using (var pix = PixConverter.ToPix(image))
                    {
                        using (var page = engine.Process(pix))
                        {
                            return page.GetText();
                        }
                    }
                }
            }
        }

        private string GetText(Bitmap img)
        {
            using (var engine = new TesseractEngine("./tessdata", "chi_sim", EngineMode.Default))
            {
                var image = img;
                {
                    using (var pix = PixConverter.ToPix(image))
                    {
                        using (var page = engine.Process(pix))
                        {
                            return page.GetText(); 
                        }
                    }
                }
            }
        }

        public string GetSex(string idStr)
        {
            if (Convert.ToInt32( idStr.ToCharArray()[idStr.Length-2])%2==0)
                return "女";
            
               
            else return "男";
        }

        public string GetDate(string idStr)
        {
            // str = GetNumber(str);
            try
            {
                string year = idStr.Substring(6, 4);
                string month = idStr.Substring(10, 2);
                string day = idStr.Substring(12, 2);
                return year + "年" + month + "月" +day+ "日";
            }
            catch { return null; }
        }

        public string GetNumber(string str)
        {
            Regex r = new Regex("X|x|\\d+\\.?\\d*");
            bool ismatch = r.IsMatch(str);
            MatchCollection mc = r.Matches(str);

            string result = string.Empty;
            for (int i = 0; i < mc.Count; i++)
            {
                result += mc[i];
            }
            return result;
        }

        public string GetChinese(string str)
        {
            Regex r = new Regex("[\u4e00-\u9fa5]");
            bool ismatch = r.IsMatch(str);
            MatchCollection mc = r.Matches(str);

            string result = string.Empty;
            for (int i = 0; i < mc.Count; i++)
            {
                result += mc[i];
            }
            return result;
        }

        /// <summary>
        /// 身份证号验证
        /// </summary>
        /// <param name="idNumber"></param>
        /// <returns></returns>
        private bool CheckIDCard(string idNumber)
        {
            long n = 0;
            if (long.TryParse(idNumber.Remove(17), out n) == false
            || n < Math.Pow(10, 16) || long.TryParse(idNumber.Replace('x', '0').Replace('X', '0'), out n) == false)
            {
                return false;//数字验证  
            }
            string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
            if (address.IndexOf(idNumber.Remove(2)) == -1)
            {
                return false;//省份验证  
            }
            string birth = idNumber.Substring(6, 8).Insert(6, "-").Insert(4, "-");
            DateTime time = new DateTime();
            if (DateTime.TryParse(birth, out time) == false)
            {
                return false;//生日验证  
            }
            string[] arrVarifyCode = ("1,0,x,9,8,7,6,5,4,3,2").Split(',');
            string[] Wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(',');
            char[] Ai = idNumber.Remove(17).ToCharArray();
            int sum = 0;
            for (int i = 0; i < 17; i++)
            {
                sum += int.Parse(Wi[i]) * int.Parse(Ai[i].ToString());
            }
            int y = -1;
            Math.DivRem(sum, 11, out y);
            if (arrVarifyCode[y] != idNumber.Substring(17, 1).ToLower())
            {
                return false;//校验码验证  
            }
            return true;  
        }
    }
}
